import { Tag, Ellipsis, InfiniteScroll } from "antd-mobile";
import "./index.scss";
import { useEffect, useState } from "react";
import { courseGet } from "../../api/course";
import { CourseType } from "../../types/course";
import CourseSkeleton from "./course-skeleton";
import { Link } from "react-router-dom";
interface CoursePropsType {
  lv1: string;
  lv2: string;
}
let page = 1;
let isFirst = true; //开关变量，控制useEffect内部逻辑执行
export default function Course(props: CoursePropsType) {
  let [courseList, setCourseList] = useState<CourseType[]>([]);
  let [hasMore, setHasMore] = useState<boolean>(true);
  // 分类筛选：分类条件变化时再执行此useEffect
  useEffect(() => {
    console.log("useEffect执行了", props);
    page = 1;
    if (!isFirst) {
      //首屏数据渲染
      courseGet({ ...props }).then((res) => {
        setCourseList(res.data.results);
        page++;
      });
    }
    return () => {
      isFirst = false;
    };
  }, [props.lv1, props.lv2]);
  // 触底执行loadMore
  const loadMore = async () => {
    // if (!isFirst) {
    console.log("触底了");
    courseGet({ ...props }, page).then((res) => {
      let { results } = res.data;
      if (results.length) {
        setCourseList([...courseList, ...results]);
        page++;
        return;
      }
      setHasMore(false); //停止触底监听
    });
    // }
  };
  return (
    <div className="cont">
      {courseList.length ? "" : <CourseSkeleton />}
      <div className="list">
        {courseList.map((item) => {
          return (
            <div className="list-item" key={item.objectId}>
              <Tag className="tag" color="rgba(0,0,0,0.3)" fill="solid">
                免费
              </Tag>
              <img className="poster" src={item.poster} alt="" />
              <Link to={`/detail/${item.objectId}`}>
                <Ellipsis className="name" content={item.name} />
                <Ellipsis className="intro" rows={2} content={item.intro} />
              </Link>
            </div>
          );
        })}
      </div>
      {courseList.length ? (
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={200} />
      ) : (
        ""
      )}
    </div>
  );
}
